package other.xsy.baidu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.Lead;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.xsy.baidu.util.HCDateUtils;
import other.xsy.baidu.util.HCXObjectService;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 同步官网数据到潜在客户
 * @Author: 黎炎松
 * @Date: 2024/5/28 17:17
 */
public class SyncWebLeadDataSchedule implements ScheduleJob, FutureTask {

    private HCXObjectService hcxObjectService = new HCXObjectService();
    private XoqlService xoqlService = XoqlService.instance();
    public static final CommonHttpClient HTTP_CLIENT = CommonHttpClient.instance();
    private final Logger logger = LoggerFactory.getLogger();
    private String LOGGER_MSG = "同步官网数据到潜在客户 ==> ";
    // 请求官网Api地址
    private String reqWebApi = "https://getech.cn/event/api";
    private int userListActIndex = 0;

    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        syncWebBaiduData();
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        new SyncWebLeadDataSchedule().syncWebBaiduData();
    }

    /**
     * 同步
     */
    public void syncWebBaiduData() {
        try {
            logger.debug(LOGGER_MSG + "开始处理");

            // 从数据配置表中获取数据
            String sql = "select id,lastSyncTime__c,syncAssistVal__c from syncConfig__c where syncKey__c = 'WEB_QZKH'";
            SyncConfig__c syncConfig = hcxObjectService.queryOne(sql, SyncConfig__c.class);
            if (syncConfig == null) {
                logger.debug(LOGGER_MSG + " 数据配置信息不存在");
                return;
            }

            // 获取同步时间
            String startDate = syncConfig.getLastSyncTime__c();
            String endDate = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME); // 同步结束时间
            // 如果为空则退回1天前
            if (StringUtils.isBlank(startDate)) {
                startDate = HCDateUtils.getDaysBeforeString(1, HCDateUtils.FORMATTIME);
            }
            logger.debug(LOGGER_MSG + " startDate: " + startDate);
            logger.debug(LOGGER_MSG + " endDate: " + endDate);

            // 读取官网事件列表
            String reqUrl = reqWebApi + "/list";

            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("page.size", "200");
            JSONObject reqDataObj = sendGetReq(reqUrl, paramsMap);
            logger.info("reqDataObj: " + reqDataObj);
            if (reqDataObj == null) {
                logger.debug(LOGGER_MSG + "没有事件列表数据");
                // 更新时间
                syncConfig.setLastSyncTime__c(endDate);
                syncConfig.setLastSyncCount__c(0L);
                hcxObjectService.update(syncConfig);
                return;
            }

            // 获取数据
            JSONArray eventList = reqDataObj.getJSONArray("content");
            logger.debug(LOGGER_MSG + "eventList: " + eventList);
            if (eventList == null) {
                logger.error(LOGGER_MSG + "获取事件列表数据异常");
                return;
            }

            // 设置创建时间范围  传入时间戳
            //paramsMap.put("st", "1620878020000");
            //paramsMap.put("et", "1716883871000");
            paramsMap.put("st", String.valueOf(Timestamp.valueOf(startDate).getTime()));
            paramsMap.put("et", String.valueOf(Timestamp.valueOf(endDate).getTime()));

            // 查询分配的用户数据 分配的官网账号标识为4
            sql = "select id,name,dimDepart from user where status = 1 and assignBdAccount__c in (4) order by createdAt";
            QueryResult<JSONObject> xoqlQuery = xoqlService.query(sql);
            List<JSONObject> userList = xoqlQuery.getRecords();
            logger.debug(LOGGER_MSG + "userList: " + userList.size());

            // 初始化下标 用来记录当前分配的用户下标
            String lastUserId = syncConfig.getSyncAssistVal__c();
            userListActIndex = 0;
            if (StringUtils.isNotBlank(lastUserId) && userList.size() > 1) {
                int index = userList.stream().map(v -> v.getString("id")).collect(Collectors.toList()).indexOf(lastUserId);
                userListActIndex = index != -1 ? index : 0;
            }

            // 根据事件列表获取数据
            logger.debug(LOGGER_MSG + "获取官网数据");
            List<Lead> addLeadList = new ArrayList<>();
            for (Object o : eventList) {
                JSONObject event = (JSONObject) o;
                // 获取潜在客户集合数据
                List leadList = getLeadList(event, paramsMap, userList);
                addLeadList.addAll(leadList);
            }
            logger.debug(LOGGER_MSG + "addLeadList: " + addLeadList.size());
            if (addLeadList.size() <= 0) {
                logger.info(LOGGER_MSG + "没有需要保存的数据");
                // 更新时间
                syncConfig.setLastSyncTime__c(endDate);
                syncConfig.setLastSyncCount__c(0L);
                hcxObjectService.update(syncConfig);
                return;
            }

            // 批量保存
            BatchOperateResult batchOperateResult = hcxObjectService.batchInsert(addLeadList);
            if (!batchOperateResult.getSuccess()) {
                logger.error(LOGGER_MSG + "批量保存数据异常: " + batchOperateResult.getErrorMessage());
                //return;
            }

            // 更新配置表信息
            syncConfig.setLastSyncTime__c(endDate);
            syncConfig.setLastSyncCount__c(Long.valueOf(addLeadList.size()));
            // 用来记录下次分配开始的用户
            if (userList.size() > 0) {
                syncConfig.setSyncAssistVal__c(userList.get(userListActIndex).getString("id"));
            }
            Boolean update = hcxObjectService.update(syncConfig);
            logger.debug(LOGGER_MSG + "更新数据同步配置: " + update);
            if (!update) {
                logger.error(LOGGER_MSG + " 更新数据同步配置异常");
                return;
            }

            logger.debug(LOGGER_MSG + "处理完成");
        } catch (ApiEntityServiceException e) {
            logger.error(LOGGER_MSG + "同步异常");
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取潜在客户数据
     *
     * @param event
     * @param userList
     * @return
     */
    public List getLeadList(JSONObject event, Map<String, Object> paramsMap, List<JSONObject> userList) throws ApiEntityServiceException {

        List<Lead> leadList = new ArrayList<>();

        // 发送请求
        Integer id = event.getInteger("id");

        JSONObject reqDataObj = sendGetReq(reqWebApi + "/detail-" + id, paramsMap);
        if (reqDataObj == null) {
            return leadList;
        }

        // 获取事件内容数据
        JSONArray colList = reqDataObj.getJSONArray("cols");
        JSONObject eventContents = reqDataObj.getJSONObject("eventContents");
        JSONArray contentList = eventContents.getJSONArray("content");
        if (contentList.size() <= 0) {
            return leadList;
        }

        // 把 colList 转换为 Map
        Map<String, String> colMap = new LinkedHashMap<>();
        for (int i = 0; i < colList.size(); i++) {
            colMap.put(colList.get(i).toString(), "col" + (i + 1));
        }

        // 获取潜在客户数据
        for (Object o : contentList) {
            JSONObject content = (JSONObject) o;
            Lead lead = getLeadData(event.getString("title"), colMap, content, userList);
            leadList.add(lead);
        }

        return leadList;
    }

    /**
     * 获取单个潜在客户数据
     * @param title
     * @param colMap
     * @param content
     * @param userList
     * @return
     */
    public Lead getLeadData(String title, Map<String, String> colMap, JSONObject content, List<JSONObject> userList) {
        Lead lead = new Lead();
        lead.setEntityType(11010001100001L); // 业务类型
        lead.setDataSource__c(3); // 1:系统 2：百度营销 3: 官网 4：天客云
        lead.setProfession__c(36); // 行业 默认：待定
        lead.setSubsectors__c(97); // 子行业 默认：待定
        lead.setProduct__c(22); // 产品待定
        lead.setStatus(1); // 潜在客户状态 默认: 未处理
        lead.setCustomerSource__c(6); // 潜在客户来源： 默认: SEO
        lead.setSourceLevel2__c(24); // 潜在客户来源二级 默认：官网
        lead.setCountry__c(45); // 国家/地区  默认：中国
        lead.setFState(39); // 省份 默认待定
        lead.setFCity(1); // 城市 默认待定
        //lead.setDimDepart(3212422568873310L); // 所属部门 默认：市场部 （不需要赋值，系统会根据 【所有人】自动赋值）
        lead.setSyncDataId__c(content.getString("id")); // id
        lead.setSyncDataType__c(title); // 类型

        lead.setCompanyName("待定"); // 公司名称
        lead.setName("待定"); // 名称

        // 获取值
        colMap.forEach((k, v) -> {
            if (k.indexOf("公司") != -1) {
                lead.setCompanyName(content.getString(v));
            } else if (k.indexOf("姓名") != -1) {
                lead.setName(content.getString(v));
            } else if (k.indexOf("手机号") != -1) {
                lead.setMobile(content.getString(v));
            } else if (k.indexOf("关注的问题") != -1) {
                lead.setComment(content.getString(v));
            } else if (k.indexOf("邮箱") != -1) {
                lead.setEmail__c(content.getString(v));
            }
        });

        // 所有人
        if (userList.size() > 0) {
            // 轮询分配给指定部门下的客户
            lead.setOwnerId(userList.get(userListActIndex).getLong("id"));
            // 判断下标是否需要重置为0
            userListActIndex++;
            if (userListActIndex == userList.size()) {
                userListActIndex = 0;
            }
        } else {
            // 如果查询不到分配用户数据，默认给到当前用户
            lead.setOwnerId(3294456680602270L);
        }

        return lead;
    }

    public JSONObject sendGetReq(String reqUrl, Map<String, Object> paramsMap) {
        // 发送请求 拼接url参数
        String params = "";
        for (String key : paramsMap.keySet()) {
            if (params == "") {
                params = "?" + key + "=" + paramsMap.get(key);
            } else {
                params += "&" + key + "=" + paramsMap.get(key);
            }
        }
        CommonData build = CommonData.newBuilder().callString(reqUrl + params)
                .callType("GET")
                .build();
        HttpResult execute = HTTP_CLIENT.execute(build);
        String result = execute.getResult();
        if (StringUtils.isBlank(result)) {
            return null;
        }
        JSONObject reqDataObj = JSONObject.parseObject(result);
        return reqDataObj;
    }

}
